package com.acme.bankapp.service.bank;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import com.acme.bankapp.domain.bank.Client;
import com.acme.exceptions.ClientExistException;

public class BankDataLoaderService {
	private final static String split0 = ";";
	private final static String split1 = "=";
	private final static String gender = "m";
	private final static String err = "No file with such name";
	private final static String account = "s";

	public void read(String path, BankService bankService) {
		File fp = new File(path);
		Scanner scanner;
		String str;
		String[] args = new String[5];
		String[] sWithEq;
		String[] sWithoutEq;
		Client client;
		int idClient;
		try {
			scanner = new Scanner(fp);
			while (scanner.hasNext()) {
				str = scanner.nextLine();
				sWithEq = str.split(split0);
				for (int i = 0; i < 5; i++) {
					sWithoutEq = sWithEq[i].split(split1);
					args[i] = sWithoutEq[1];
				}

				if (args[4].equals(gender)) {
					client = new Client(args[3], true);
				} else {
					client = new Client(args[3], false);
				}

				try {
					idClient = bankService.addClient(client);

				} catch (ClientExistException e) {
					idClient = e.idClient;
				}

				if (args[0].equals(account)) {
					bankService.bank.clients.get(idClient).openAccount(
							Double.parseDouble(args[1]));
				} else {
					bankService.bank.clients.get(idClient).openAccount(
							Double.parseDouble(args[1]),
							Double.parseDouble(args[2]));
				}

			}
			scanner.close();

		} catch (FileNotFoundException e) {
			System.out.println(err);
		}
	}
}
